HTML tables are used to organize and display data in a tabular format. Tables are made up of rows and columns, defined using a combination of the following elements:
Basic Structure
The basic structure of an HTML table includes the <table>
, <tr>
, <th>
, and <td>
elements.
Example:
html
<table>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
<tr>
<td>Data 1</td>
<td>Data 2</td>
<td>Data 3</td>
</tr>
<tr>
<td>Data 4</td>
<td>Data 5</td>
<td>Data 6</td>
</tr>
</table>
Table Elements
<table>
: The container element for the table.
<tr>
: Represents a table row.
<th>
: Defines a header cell in a table, typically bold and centered.
<td>
: Defines a standard data cell in a table.
Additional Elements
<caption>
: Provides a title or caption for the table.
html
<table>
<caption>Employee Information</caption>
</table>
<thead>
: Groups the header content in a table.
html
<table>
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
</thead>
</table>
<tbody>
: Groups the body content in a table.
html
<table>
<thead>
</thead>
<tbody>
<tr>
<td>Data 1</td>
<td>Data 2</td>
<td>Data 3</td>
</tr>
</tbody>
</table>
<tfoot>
: Groups the footer content in a table.
html
<table>
<thead>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td>Footer 1</td>
<td>Footer 2</td>
<td>Footer 3</td>
</tr>
</tfoot>
</table>
Example with Full Structure
Here' an example that includes all the table elements:
html
<table>
<caption>Sales Report</caption>
<thead>
<tr>
<th>Month</th>
<th>Sales</th>
<th>Expenses</th>
<th>Profit</th>
</tr>
</thead>
<tbody>
<tr>
<td>January</td>
<td>$10,000</td>
<td>$5,000</td>
<td>$5,000</td>
</tr>
<tr>
<td>February</td>
<td>$12,000</td>
<td>$6,000</td>
<td>$6,000</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Total</td>
<td>$22,000</td>
<td>$11,000</td>
<td>$11,000</td>
</tr>
</tfoot>
</table>
Styling Tables with CSS
You can style tables using CSS to improve their appearance.
Example:
css
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
font-weight: bold;
}
tr:nth-child(even) {
background-color: #f9f9f9;
}
caption {
caption-side: top;
font-weight: bold;
margin-bottom: 10px;
}
By using these elements and styles, you can create well-structured and visually appealing tables in HTML. Let me know if you have any specific scenarios or further questions about table elements!